package my.springboot.validation.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class Main {  
	  
    public static void main(String [] args ){  
//        Person person = new Person();
//        person.setUsername("");
//        person.setAge(1);

        Person person1 = new Person();
        Object o = person1;
        try {
            Main.validate(o);
        } catch (ValidationException e) {
            e.printStackTrace();
        }

//        List<User> users =new ArrayList<User>();
//        users.add(new User());
//        person.setUsers(users);
//        try {
//            Main.validate(person);
//        } catch (ValidationException e) {
//            System.out.println(e.getMessage());  //输出结果是：用户名不能为空
//        }
    }  
  
    public static <T>  void validate(T t) throws ValidationException {  
        ValidatorFactory vFactory = Validation.buildDefaultValidatorFactory();  
        Validator validator = vFactory.getValidator();  
        Set<ConstraintViolation<T>> set =  validator.validate(t);  
        if(set.size()>0){  
            for(ConstraintViolation<T> val : set){  
                throw new ValidationException(val.getMessage());              
            }  
        }  
  
    }  
}  
